﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FeedAgregator;
using System.Reflection;
using System.Text.RegularExpressions;

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadCategories();
            LoadTags();
            LoadNewsNumbers(); 
            LoadSmallNewsBlocks();
            LoadItemsWithImages();
            LoadObjects();
        }
    }

    private void LoadObjects()
    {
        DateLabel.Text = DateTime.Now.Date.ToString("dd.MM.yyyy");
    }

    private void LoadItemsWithImages()
    {
        NewsWithPicturesListView.DataSource = DataAccessHelper.GetItemsWithImages();
        NewsWithPicturesListView.DataBind();
    }



    private void LoadSmallNewsBlocks()
    {
        LoadMostReaded();

        LoadForMen();
    }

    private void LoadForMen()
    {
        BlogsListView.DataSource = DataAccessHelper.GetLastForMen();
        BlogsListView.DataBind();
    }

   

    private void LoadMostReaded()
    {
        MostReadedListView.DataSource = DataAccessHelper.GetMostReaded();
        MostReadedListView.DataBind();
    }

    private void LoadNewsNumbers()
    {
        long totalNewsNumber = DataAccessHelper.GetTotalNewsNumber();
        long last24NewsNumber = DataAccessHelper.GetLast24NewsNumber();
        Last24NewsNumberLabel.Text = last24NewsNumber.ToString();
        TotalNewsNumberLabel.Text = totalNewsNumber.ToString();
    }

    private void LoadTags()
    {
        List<Tag> tags = DataAccessHelper.GetAllTags();
        TagCloud.DataTextField = "TagName";
        TagCloud.DataTitleField = "TagName";
        TagCloud.DataTextField = "TagName";
        TagCloud.DataWeightField = "Weight";
        TagCloud.DataHrefField = "TagName";
        TagCloud.DataHrefFormatString = "~/?tag={0}";
        TagCloud.DataSource = tags;

        TagCloud.DataBind();
        //TagCloud.DataBind();

    }

    protected void NewsWithPicturesListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = e.Item as ListViewDataItem;
            object feedItem = dataItem.DataItem;
            Type feedItemDynamicType = feedItem.GetType();
            PropertyInfo itemContentPropertyInfo = feedItemDynamicType.GetProperty("ItemContent");
            string itemContent = itemContentPropertyInfo.GetValue(feedItem, null) as string;
            Image ContentImage = e.Item.FindControl("ContentImage") as Image;
            if (itemContent!=null && itemContent.Contains(@"<img"))
            {
                Match imageMatch = Regex.Match(itemContent, @"(?<=img\s+src\=[\x27\x22])(?<Url>[^\x27\x22]*)(?=[\x27\x22])");
                if (imageMatch.Captures != null && imageMatch.Captures.Count > 0)
                {
                    string imageSrc = imageMatch.Captures[0].ToString();

                    ContentImage.ImageUrl = imageSrc;
                }

            }
            else
            {
                ContentImage.Visible = false;
            }
        }
    }



    private void LoadCategories()
    {
        List<FeedCategory> categories = DataAccessHelper.GetAllCategories();
        CategoriesListView.DataSource = categories;
        CategoriesListView.DataBind();
    }
    protected void SearchButton_Click(object sender, EventArgs e)
    {
        if (SearchTextBox.Text.Length > 0)
        {
            //insert in the search archive
            using (FeedSignalDataContext ctx = new FeedSignalDataContext())
            {
                var query = from sarch in ctx.SearchArchives
                            where sarch.SearchPhrase == SearchTextBox.Text
                            select sarch;
                FeedAgregator.SearchArchive archiveToAdd = null;
                if (query.Count() > 0)
                {
                    archiveToAdd = query.Single();
                }

                if (archiveToAdd == null)
                {
                    archiveToAdd = new FeedAgregator.SearchArchive();
                    archiveToAdd.SearchPhrase = SearchTextBox.Text;
                    archiveToAdd.TimesSearched = 1;
                    archiveToAdd.FirstSearchedOn = DateTime.Now;
                    ctx.SearchArchives.InsertOnSubmit(archiveToAdd);
                }
                else
                {
                    archiveToAdd.TimesSearched += 1;
                    archiveToAdd.LastSearchedOn = DateTime.Now;
                }
                ctx.SubmitChanges();

            }
            if (SearchOptionDropDownList.SelectedIndex == 0)
            {
                Response.Redirect(string.Format("?search={0}&type=0", SearchTextBox.Text));
            }
            else
            {
                Response.Redirect(string.Format("?search={0}&type=1", SearchTextBox.Text));
            }
        }

    }
}
